package com.x2.core.constant.factory;

import cn.hutool.core.bean.BeanUtil;
import com.x2.base.auth.model.LoginUser;
import com.x2.core.auth.LoginUserExtendProxy;
import com.x2.core.constant.state.ManagerStatus;
import com.x2.modular.system.entity.User;
import com.x2.modular.system.model.UserBean;
import org.springframework.beans.BeanUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户创建工厂 *
 *
 * @author x2
 * @date 2017-05-05 22:43
 */
public class UserFactory {

    /**
     * 根据请求创建实体
     *
     * @param userDto：用户对象
     * @param md5Password：密码
     * @param salt：加密
     * @return 结果
     */
    public static User createUser(User userDto, String md5Password, String salt) {
        if (userDto == null) {
            return null;
        } else {
            User user = new User();
            BeanUtils.copyProperties(userDto, user);
            user.setCreateTime(new Date());
            user.setStatus(ManagerStatus.OK.getCode());
            user.setPassword(md5Password);
            user.setSalt(salt);
            return user;
        }
    }


    /**
     * 过滤不安全字段并转化为map
     */
    public static Map<String, Object> removeUnSafeFields(User user) {
        if (user == null) {
            return new HashMap<>(0);
        } else {
            Map<String, Object> map = BeanUtil.beanToMap(user);
            map.remove("password");
            map.remove("salt");
            return map;
        }
    }

    /**
     * 通过用户表的信息创建一个登录用户
     */
    public static LoginUser createLoginUser(User user) {
        LoginUser loginUser = new LoginUser();
        if (user == null) {
            return loginUser;
        }
        LoginUserExtendProxy proxy = LoginUserExtendProxy.build(loginUser);
        proxy.setId(user.getUserId());
        proxy.setAccount(user.getAccount());
        proxy.setName(user.getName());

        proxy.setUserType(user.getUserType());
        proxy.setDeptId(user.getDeptId());
        proxy.setDeptName(ConstantFactory.me().getDeptName(user.getDeptId()));

        if (user.getAvatar() != null) {
            proxy.setAvatar("/api/system/preview/" + user.getAvatar());
        }
        return proxy.getLoginUser();
    }

    public static void setUserPropNull(UserBean user) {

    }
}
